'use strict'

const {Products,Op} = require('../model');

let fn_list = async(ctx,next)=>{//列表
    let keyword = ctx.request.query.keyword || '';
    if (keyword) {
        let list = await Products.findAll({
            where:{
                [Op.or]:[
                    {id : isNaN(keyword) ? 0 : parseInt(keyword)},
                    {Abstract: keyword},
                    {Title: keyword},
                    {Content: keyword},
                    {Classify: keyword},
                    {Author: keyword},
                    {ReleaseTime: keyword},
                ]
            },
            order:['id']
        });
        ctx.body={
           code:1000,
           data:list,
           msg:"请求成功！"
        };
    } else {
        let list = await Products.findAll()
        ctx.body={
            code:1000,
            data:list,
            msg:"请求成功！"
         };
    }
}

let fn_getbyid = async(ctx,next)=>{//获取指定Id
    let id = ctx.request.params.id;
    let product = await Products.findByPk(id);
    if (product) {
        ctx.body={
            code:1000,
            data:product,
            msg:"获取指定记录成功！"
         };
    } else {
        ctx.body={
            code:900,
            data:'',
            msg:"获取指定记录失败！"
         };
    }
}

let fn_post = async(ctx,next)=>{//新增
    let obj = ctx.request.body;
    await Products.create(obj);
    ctx.body=obj;
}

let fn_put = async(ctx,next)=>{//编辑
    let id = ctx.request.params.id;
    let product = await Products.findByPk(id);
    let obj = ctx.request.body;
    if (product) {
        Products.update(obj,{
            where:{
                id:id
            }
        });
        ctx.body={
            code:1000,
            data:Products,
            msg:"编辑成功！"
        }
    } else {
        ctx.body={
            code:900,
            data:'',
            msg:"编辑失败！"
        }
    }
}

let fn_delete = async(ctx,next)=>{//删除
    let id = ctx.request.params.id;
    let product = await Products.findByPk(id);
    if (product) {
        Products.destroy({
            where:{
                id:id
            }
        });
        ctx.body={
            code:1000,
            data:{id},
            msg:"删除成功！"
        }
    } else {
        ctx.body={
            code:400,
            data:null,
            msg:"删除失败！"
        }
    }
}

module.exports={
    'get /product': fn_list,
    'get /product/:id': fn_getbyid,
    'post /product': fn_post,
    'put /product/:id': fn_put,
    'delete /product/:id': fn_delete
}